<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="120px"
      v-loading="formLoading"
    >
      <el-form-item label="年份" prop="years">
        <el-date-picker
          v-model="formData.years"
          type="year"
          placeholder="请选择年份"
          format="YYYY"
          value-format="YYYY"
          style="width: 100%"
        />
      </el-form-item>
      <el-form-item label="假期类型" prop="standardId">
        <el-select v-model="formData.standardId" placeholder="请选择假期类型" @change="holidayChange">
          <el-option
              v-for="item in holidayTypeList"
              :key="item.id"
              :label="item.leaveName"
              :value="item.id"
          />
        </el-select>
      </el-form-item>
      <!-- <el-form-item :label="'标准'+(formData.leaveName === '调休' ? '小时' : '天')+'数'" prop="standardDays">
        <el-input v-model="formData.standardDays" placeholder="请输入标准天/小时数"  />
      </el-form-item> -->
      <el-form-item label="新增天数" prop="remaining">
        <el-input v-model="formData.remaining" placeholder="请输入新增天数" >
          <template #append>{{formData.leaveName === '调休' ? '小时' : '天'}}</template>
        </el-input>
      </el-form-item>

      <el-form-item label="员工姓名" prop="userId">
        <UserSelect @node-change="handleNodeChange" v-model="formData.userId" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { EmployeeLeaveBalanceApi, EmployeeLeaveBalanceVO } from '@/api/oa/employeeleavebalance'
import UserSelect from '@/views/system/user/UserSelect.vue'

/** 员工假期余额管理 表单 */
defineOptions({ name: 'EmployeeLeaveBalanceForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  years: undefined as string | undefined,
  leaveType: undefined,
  leaveName: undefined,
  standardDays: undefined,
  remaining: undefined,
  userName: undefined as string | undefined,
  standardId: undefined,
  userId: undefined as number | undefined,
})
const formRules = reactive({
  years: [{ required: true, message: '年份不能为空', trigger: 'blur' }],
  standardId: [{ required: true, message: '假期类型不能为空', trigger: 'change' }],
  standardDays: [{ required: true, message: '标准天数不能为空', trigger: 'blur' }],
  remaining: [{ required: true, message: '新增天数不能为空', trigger: 'blur' }],
  userName: [
    {
      required: true,
      message: '员工姓名不能为空',
      trigger: 'blur',
      validator: (_rule: any, value: any, callback: any) => {
        if (formData.value.userId) return callback();
        if (!value) return callback(new Error('员工姓名不能为空'));
        return callback();
      }
    }
  ],
})
const formRef = ref() // 表单 Ref
let holidayTypeList = ref() // 假期类型

/** 打开弹窗 */
const open = async (type: string, id?: number, userId?: number, userName?: string, years?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 新增时自动带入 userId、userName、years
  if (type === 'create') {
    if (userId) formData.value.userId = userId
    formData.value.userName = userName // 无论有无都赋值
    if (years) formData.value.years = String(years)
  }
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      const info = await EmployeeLeaveBalanceApi.getEmployeeLeaveBalance(id)
      // 确保年份字段为字符串格式，以便 el-date-picker 正确回显
      if (info.years) {
        info.years = String(info.years)
      }
      formData.value = info
    } finally {
      formLoading.value = false
    }
  }
  getHolidayStandardsPage()
}

const getHolidayStandardsPage = async () => {
  try{
    const params = {pageNo: 1, pageSize: 10}
    params.pageSize = 100
    const data = await EmployeeLeaveBalanceApi.getHolidayStandardsPage(params)

    holidayTypeList = data.list
  } finally {

  }
}

const holidayChange = async (id: number) => {
  const info = await EmployeeLeaveBalanceApi.getHolidayStandards(id)
  formData.value.standardDays = info.days
  formData.value.leaveType = info.leaveType
  formData.value.leaveName = info.leaveName
  formData.value.standardId = info.id
}

defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交前补全 leaveName 和 leaveType
  if (formData.value.standardId && holidayTypeList && Array.isArray(holidayTypeList)) {
    const selected = holidayTypeList.find(item => item.id === formData.value.standardId)
    if (selected) {
      formData.value.leaveName = selected.leaveName
      formData.value.leaveType = selected.leaveType
    }
  }
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as EmployeeLeaveBalanceVO
    if (formType.value === 'create') {
      await EmployeeLeaveBalanceApi.createEmployeeLeaveBalance(data)
      message.success(t('common.createSuccess'))
    } else {
      await EmployeeLeaveBalanceApi.updateEmployeeLeaveBalance(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    years: undefined as string | undefined,
    leaveType: undefined,
    leaveName: undefined,
    standardDays: undefined,
    remaining: undefined,
    userName: undefined as string | undefined,
    standardId: undefined,
    userId: undefined as number | undefined,
  }
  formRef.value?.resetFields()
}

/** 员工被点击事件 */
const handleNodeChange = async (row) =>{
  formData.value.userId = row.id
  formData.value.userName = row.nickname
}
</script>
